package com.wlz.http;

import com.alibaba.fastjson.JSONObject;
import com.wlz.entity.StateRequest;
import com.wlz.entity.request.f1.F1Request;
import com.wlz.util.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.util.List;

/**
 * @author wlz
 * @date 2022-11-26  1:20 上午
 */
@Slf4j
public class OkHttpCarChangeState {

    private static final String URL = "https://ota.bjev.com.cn/api/c62/car/changeState";

    private static final String FILE_URL = "/Users/wlz/Desktop/C62cc6f5a6c-889f-4a4f-82fe-508ebb3aca1f.xlsx";

    public static void main(String[] args) throws IOException, InterruptedException {
        List<String> list = ExcelUtils.getVins(FILE_URL);
        int count = 0;
        int successCount = 0;
        if (list != null && list.size() > 0) {
            for (String vinNo : list) {
//            String vinNo = list.get(0);
            StateRequest request = new StateRequest();
                request.setType(0);
                request.setVinNo(vinNo);
                request.setEndTime("2023-03-29 00:00:00");
                Response response = sendHttp(JSONObject.toJSONString(request));
                count++;
//                Thread.sleep(500);
                JSONObject result = JSONObject.parseObject(response.body().string());
                if (0 == result.getInteger("code")) {
                    successCount++;
                }
                log.info("VIN {}  response body {}", vinNo, result.toJSONString());
            }
        }
        log.info("count = {}", count);
        log.info("successCount = {}", successCount);
    }

    /**
     *  发送请求
     * @param param
     * @return
     */
    public static Response sendHttp(String param) throws IOException {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, param);
        Request request = new Request.Builder()
                .url(URL)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyb2xlSW5mbyI6IntcInJvbGVJZFwiOlwiMTU4NDZjNzEtZDRhOS00ZTA1LWE1MDktZmNlYzVhY2U3MWIxXCIsXCJyb2xlTmFtZVwiOlwi5bel5Y6CXCIsXCJyb2xlVHlwZVwiOjQsXCJyb2xlU3ViVHlwZVwiOjEsXCJ3ZWlnaHRcIjo0MDAsXCJpc1N5c1wiOjAsXCJkYXRhU2NvcGVcIjowLFwiaXNMYXJnZVZlcnNpb25cIjowfSIsImNhclR5cGVJbmZvIjoie1wiY2FyVHlwZUlkXCI6XCIxN2I2ZjM5MS02YTFlLTRlZGQtYjViMS1jYTJlMGY1ZTEzZDhcIixcImNhclR5cGVOYW1lXCI6XCJDNjJcIn0iLCJ1c2VyVHlwZSI6IlBMQVRGT1JNIiwiaWQiOiI2MTYzZTU4ZC0yNTQ2LTRhZGUtYjIzNy01YzlkMDE1YTQ0MWYiLCJleHAiOjE2NzUxMzk4MzQsImlhdCI6MTY3NTEzMjYzNH0.5lWcp4J48dpIvyGQFizsA4efGns73kefFbtrSzsk5SA")
                .build();
        Response response = client.newCall(request).execute();
        return response;
    }
}
